//
//  Piece.m
//  CheckersGame
//
//  Created by Guest User on 11-12-07.
//  Copyright (c) 2011 __MyCompanyName__. All rights reserved.
//

#import "Piece.h"

@implementation Piece

@synthesize boardView;



- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    NSLog(@"Touch");
    UITouch *touch = [[event allTouches] anyObject];
    
    CGPoint location = [touch locationInView:self];
    
    if ([gameState getBoardRef]->iswhiteturn == self->whitepiece && [[gameState currentPlayer] needsPieceInteraction]){
        gameState.selectPosition = pos;
        gameState.pieceIsSelected = YES;
        [boardView setNeedsDisplay];

        NSLog(@"Touched!");        
    }
}
- (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    int size = self.frame.size.width;
    if (gameState.pieceIsSelected) {
        
        CGPoint location = [touch locationInView:boardView.superview];
        if (pos.x == gameState.selectPosition.x && pos.y == gameState.selectPosition.y){
            self.center = CGPointMake(location.x, location.y);
            [self.superview bringSubviewToFront: self];
        }
    }
        
}
        
- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    BOOL didmove = NO;
    int size = self.frame.size.height;
    if (gameState.pieceIsSelected) {
        
        CGPoint location = [touch locationInView:boardView];
        if (!(location.x < 0 || location.y < 0 || 
            location.x > boardView.frame.size.width || location.y > boardView.frame.size.height)){
            CheckersMove move;
            move.from = pos;
            
            printf("Location %g %g\n", location.x, location.y);
            move.to.y = ((int)location.x)/size;
            move.to.x = (7) - ((int)location.y)/size; 
            printf("move is %d %d\n", move.to.x, move.to.y);
            
            if (move.to.x%2 == move.to.y%2 && chbIsValidMove([gameState getBoardRef], &move)) {
                NSLog(@"Overriding move");
                [[gameState currentPlayer] overrideNextMove: &move];
                didmove = YES;
                self.frame = CGRectMake(move.to.y*size + 20, (280-(move.to.x+1)*size) + 40, size,size);
            }
            
        }
        if (!didmove)
        if (pos.x == gameState.selectPosition.x && pos.y == gameState.selectPosition.y){
            self.frame = CGRectMake(pos.y*size + 20, (280-(pos.x+1)*size) + 40, size,size);
        }
        gameState.pieceIsSelected = NO;
        [boardView setNeedsDisplay];
    }
}


- (id) initWithPos: (CheckersPos*) p Colour: (BOOL) w View: (UIView*) ui Size: (int) size Game: (CheckersGameState*) game{
    self = [super initWithFrame: 
            CGRectMake(p->y*size + 20, 
                       (280-(p->x+1)*size) + 40,
                       size,size)];
    if (self){
        self->gameState = game;
        
        memcpy(&pos, p, sizeof(CheckersPos));
        self->boardView = ui;
        self->whitepiece = w;
        self.backgroundColor = [UIColor clearColor];
    }
    return self;
}

-(IBAction) onDrag : (id) sender {
    
}
-(IBAction) onRelease : (id) sender {
    
}
-(IBAction) onCapture : (id) sender{
    
}


+(NSArray*) pieceArrayFromBoard  : (CheckersGameState*) game View: (UIView*) ui{
    NSMutableArray* ret = [[NSMutableArray alloc] init];
    CheckersPos pos;
    piece_t p;
    CGFloat size = 280/8 ;// Block size on the board 
    
    for (pos.y = 0; pos.y < BOARD_H; pos.y++){
        for (pos.x = 0; pos.x < BOARD_W; pos.x++){
            if (pos.x%2 == pos.y%2) {
                p = chbGetPiece( [game getBoardRef], &pos);
                if (p != NO_PIECE){
                    [ret addObject: 
                     [[Piece alloc] initWithPos:&pos Colour: (p > 0) View: ui Size: size Game: game]];    
                }
            }
        }
    }
    return ret;
}

// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    piece_t piece;
    CGContextRef c = UIGraphicsGetCurrentContext();
    if (whitepiece)
        CGContextSetRGBFillColor(c,0x80/255.0,0,0,1);
    else
        CGContextSetRGBFillColor(c,0,0,0,1);  
    
    CGContextAddEllipseInRect(c, self.bounds);
    
    CGContextDrawPath(c,kCGPathFill);
    
    piece = chbGetPiece([gameState getBoardRef], &pos);
    if ( abs(piece) == KING_PIECE) {
        c = UIGraphicsGetCurrentContext();
        CGContextSetRGBFillColor(c,0.7,0.7,0,1);  
        CGRect subrect = CGRectMake(self.bounds.origin.x+5, self.bounds.origin.y+5, self.bounds.size.width - 10, self.bounds.size.height - 10);
        CGContextAddEllipseInRect(c, subrect);
        
        CGContextDrawPath(c,kCGPathFill);
    }
    //CGContextClosePath(c);
    // CGContextDrawPath(c,kCGPathFill);
}

@end
